//
//  Utils.m
//  CGNProject
//
//  Created by Michael Shen on 9/21/15.
//  Copyright (c) 2015 Dextrys. All rights reserved.
//

#import "Utils.h"
//#import "DataSigner.h"

@implementation Utils

+(NSString*)getUrlWithAction:(NSString *)action{
    NSString *urlString = [NSString stringWithFormat:@"%@%@",ServerAddress,action];
    return urlString;
}

+ (NSString *)getUrlWithAction:(NSString *)action parmasAndKeys:(NSString *)first, ... NS_REQUIRES_NIL_TERMINATION{
    va_list args;
    va_start(args, first); // scan for arguments after firstObject.
    NSString *urlString = [self getUrlWithBaseUrl:ServerAddress action:action method:nil first:first args:args];
    va_end(args);
    return urlString;
}

+ (NSString *)getUrlWithBaseUrl:(NSString *)baseUrl action:(NSString *)action method:(NSString *)method first:(NSString *)first args:(va_list)args {
    
//    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:[Utils defaultParametersWithPlatform:platformId]];
//    
//    if (method != nil) {
//        [parameters setObject:method forKey:@"method"];
//    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    for (NSString *object = first; object != nil; object = va_arg(args,NSString*)) {
        NSString *key = va_arg(args,NSString*);
        if(key != nil){
            if (![object isMemberOfClass:[NSString class]]) {
                object = [object description];
            }
            [parameters setObject:object forKey:key];
        }
    }
    
    NSMutableString *urlString = [NSMutableString stringWithString:baseUrl];
    [urlString appendFormat:@"%@?",action];
    NSMutableArray *keyAndParmas = [NSMutableArray array];
    for (NSString *key in parameters) {
        if (![urlString hasSuffix:@"?"]) {
            [urlString appendString:@"&"];
        }
        NSString *object = [parameters objectForKey:key];
        //编码
        [urlString appendFormat:@"%@=%@",key,object];
        [keyAndParmas addObject:[NSString stringWithFormat:@"%@=%@",key,object]];
    }
    
    //算32位MD5
//    NSMutableString *allKeyAndPrama = [NSMutableString string];
//    [keyAndParmas sortUsingSelector:@selector(compare:)];
//    for(NSString *string in keyAndParmas){
//        [allKeyAndPrama appendString:string];
//    }
//    [allKeyAndPrama appendString:Wo116114HttpAPISecret];
//    NSString *api_md5 = [Utils md5Encrypt:allKeyAndPrama];
//    [urlString appendFormat:@"&%@=%@",@"api_md5",api_md5];
    urlString = [self getTheExUrlWithUrl:urlString];
    
    return urlString;
}

+(NSMutableString*)getTheExUrlWithUrl:(NSMutableString*)urlString{
    [urlString appendFormat:@"&%@=%@",@"deviceUUID",[[UIDevice currentDevice] uniqueDeviceIdentifier]];
    NSString *shortVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [urlString appendFormat:@"&%@=%@",@"clientVersion",shortVersion];
    return urlString;
}

+ (UIImage *)createImageWithColor: (UIColor *) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

+(void)ScreenShot:(UIView*)view{
         //这里因为我需要全屏接图所以直接改了，宏定义iPadWithd为1024，iPadHeight为768，
     //    UIGraphicsBeginImageContextWithOptions(CGSizeMake(640, 960), YES, 0);     //设置截屏大小
         UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT), YES, 0);     //设置截屏大小
         [[view layer] renderInContext:UIGraphicsGetCurrentContext()];
         UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();
         CGImageRef imageRef = viewImage.CGImage;
     //    CGRect rect = CGRectMake(166, 211, 426, 320);//这里可以设置想要截图的区域
         CGRect rect = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);//这里可以设置想要截图的区域
         CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
         UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
         UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存图片到照片库
    }

+ (UIImage *) captureScreen {
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIImage *img = nil;
    if (keyWindow) {
        CGRect rect = [keyWindow bounds];
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [keyWindow.layer renderInContext:context];
        img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
   
//    UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);//保存图片到照片库
    return img;
}

+(NSString*)intToString:(int)v{
    return [NSString stringWithFormat:@"%d",v];
}

+(NSString*)doubleToString:(double)v{
    return [NSString stringWithFormat:@"%f",v];
}

+(NSDate*)stringToDate:(NSString*)timeString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:timeString];
    return date;
}

+(NSString*)dateToStringHHMM:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSString *currentDateStr = [dateFormatter stringFromDate: date];
    return currentDateStr;
}



+(NSString*)dateToString:(NSDate*)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate: date];
    return currentDateStr;
}

+(NSDate*)stringChineseToDate:(NSString*)timeString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY年MM月dd日"];
    NSDate *date = [dateFormatter dateFromString:timeString];
    return date;
}

#pragma mark- YY-MM-dd HH:mm:ss to YY-MM-dd
+(NSString*)dateConvert:(NSString*)timeString{
    return [self dateChineseToString:[self stringToDate:timeString]];
}

+(NSString*)dateChineseToString:(NSDate*)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentDateStr = [dateFormatter stringFromDate: date];
    return currentDateStr;
}

+(NSString*)dateToThisString:(NSDate*)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    NSString *currentDateStr = [dateFormatter stringFromDate:date];
    return currentDateStr;
}

+(NSString*)changeTheDateFormat:(NSString*)string{
    return [Utils dateToThisString:[Utils stringToDate:string]];
}

+(NSString*)dateFrom1970s:(long)dateInt{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:dateInt];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *string = [dateFormatter stringFromDate:date];
    return string;
}

+(NSString*)yearFrom1970s:(long)dateInt{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:dateInt];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY"];
    NSString *string = [dateFormatter stringFromDate:date];
    return string;
}

+(NSString*)dateProductFrom1970s:(long)dateInt{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:dateInt];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY/MM/dd"];
    NSString *string = [dateFormatter stringFromDate:date];
    return string;
}

+(NSString*)dataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

+(NSString*)changeTheNullString:(NSString*)string{
    return string?string:@"";
}

+(NSNumber*)changeTheNullNumber:(NSNumber*)number{
    return number?number:[NSNumber numberWithInt:0];
}

//注意和componentsSeparatedPhoneNumberString联用
+ (void)callPhone:(NSString *)phoneNumber{
    NSMutableString *telNumber = [NSMutableString string];
    for (int i = 0; i < [phoneNumber length]; i ++) {
        NSString *subString = [phoneNumber substringWithRange:NSMakeRange(i, 1)];
        if ([subString isEqualToString:@"转"]) {
            break;
        }
        if ([subString isEqualToString:@"+"]
            ||[subString isEqualToString:@"0"]
            ||[subString integerValue] > 0) {
            [telNumber appendString:subString];
        }
    }
    
    if ([telNumber length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您拨打的是空号码" delegate:nil cancelButtonTitle:LocalizedLanguage(@"OK") otherButtonTitles: nil];
        [alert show];
        return;
    }
    
    NSString *deviceType = [UIDevice currentDevice].model;
    if([deviceType  isEqualToString:@"iPod touch"]||[deviceType  isEqualToString:@"iPad"]||[deviceType  isEqualToString:@"iPhone Simulator"]){//
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您的设备不能打电话" delegate:nil cancelButtonTitle:LocalizedLanguage(@"OK") otherButtonTitles: nil];
        [alert show];
    }else {
        NSString *urlString = [NSString stringWithFormat:@"tel://%@",telNumber]; //number为号码字符串 如果使用这个方法 结束电话之后会进入联系人列表
        
        //        NSString *urlString = [[NSString alloc] initWithFormat:@"telprompt://%@",telNumber]; //而这个方法则打电话前先弹框  是否打电话 然后打完电话之后回到程序中 网上说这个方法可能不合法 无法通过审核
        
        NSURL *telUrl = [NSURL URLWithString:urlString];
        //        [[UIApplication sharedApplication] openURL:telUrl];
        
        UIWebView *callWebview =[[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:telUrl]];
        //记得添加到view上
        [[UIApplication sharedApplication].keyWindow addSubview:callWebview];
    }
    
}

+(NSString*)getCreateNewTime:(NSDate*)date{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    return [dateFormat stringFromDate:date];
}

+(UIColor*)getTheRamdomColor{
    int value = arc4random() % (3+1);//0-x随机数
    UIColor *color;
    switch (value) {
        case 0:
            color = ColorRGB(146, 228, 208, 1.0f);
            break;
        case 1:
            color = ColorRGB(106, 184, 227, 1.0f);
            break;
        case 2:
            color = ColorRGB(237, 114, 115, 1.0f);
            break;
        case 3:
            color = ColorRGB(254, 222, 50, 1.0f);
            break;
        default:
            break;
    }
    return color;
}


+(NSString*)getAppVersion{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

}

//考虑Retina屏
+ (UIImage *)reImage:(UIImage *)image toSize:(CGSize)reSize {
    CGImageRef imgRef = image.CGImage;
    CGSize srcSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    if (CGSizeEqualToSize(srcSize, reSize)) {
        return image;
    }
    
    UIGraphicsBeginImageContextWithOptions(reSize, NO, 0);//[UIScreen mainScreen].scale
    
    //
    //    CGContextRef context = UIGraphicsGetCurrentContext();
    //    //为上下文设置anti-aliasing反锯齿是开还是关，anti-aliasing是一个图形状态参数
    //    CGContextSetShouldAntialias(context, NO);
    //    //为上下文设置Interpolation质量
    //    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    //    //设置混合模式
    //    CGContextSetBlendMode(context, kCGBlendModeCopy);
    //    //CGPointZero等同于CGPointMake(0, 0).从（0,0）开始把image这幅图画到当前上下文中
    //    //[image drawAtPoint:CGPointZero];
    //    //UIGraphicsEndImageContext();
    //
    //
    //    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    //    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    //
    //    UIGraphicsEndImageContext();
    //    return scaledImage;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // Set the quality level to use when rescaling
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    //CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, reSize.height);
    
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return scaledImage;
}

+ (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

+(UIImage*)imageWithNewName:(NSString*)name{
    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    
    NSString *filePath = [bundlePath stringByAppendingPathComponent:name];
    
    return [UIImage imageWithContentsOfFile:filePath];
}

+(UIImage*)imageCompressWithSimple:(UIImage*)image scale:(float)scale
{
    CGSize size = image.size;
    CGFloat width = size.width;
    CGFloat height = size.height;
    scale = size.width/SCREEN_WIDTH;
    CGFloat scaledWidth = width/scale;
    CGFloat scaledHeight = height/scale;
    UIGraphicsBeginImageContext(size); // this will crop
    [image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
    UIImage* newImage= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}




+(NSString*)covertIntgerToString:(NSInteger)integer{
    NSString *string = [NSString stringWithFormat:@"%ld",integer];
    return string;
}

+(UIFont*)systemDefaultFontOfSize:(CGFloat)size{
    return [UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:size];
    
}

+(BOOL)hasGetPhotoMission{
    NSString *tipTextWhenNoPhotosAuthorization; // 提示语
    // 获取当前应用对照片的访问授权状态
    ALAuthorizationStatus authorizationStatus = [ALAssetsLibrary authorizationStatus];
    // 如果没有获取访问授权，或者访问授权状态已经被明确禁止，则显示提示语，引导用户开启授权
    if (authorizationStatus == ALAuthorizationStatusRestricted || authorizationStatus == ALAuthorizationStatusDenied) {
        NSDictionary *mainInfoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [mainInfoDictionary objectForKey:@"CFBundleDisplayName"];
        tipTextWhenNoPhotosAuthorization = [NSString stringWithFormat:@"请在设备的\"设置-隐私-照片\"选项中，允许%@访问你的手机相册", appName];
        // 展示提示语
        [BlockAlertView showAlertWithTitle:tipTextWhenNoPhotosAuthorization message:nil alertViewStyle:UIAlertViewStyleDefault block:^(id clickView, NSInteger index) {
            
        } cancelButtonTitle:@"确定" otherButtonTitles:nil];
        return NO;
    }else{
        return YES;
    }
    
}

+(BOOL)hasTakePhotoMission{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted||authStatus == AVAuthorizationStatusDenied) {
        NSDictionary *mainInfoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [mainInfoDictionary objectForKey:@"CFBundleDisplayName"];
        NSString *tipTextWhenNoPhotosAuthorization = [NSString stringWithFormat:@"请在设备的\"设置-隐私-相机\"选项中，允许%@访问你的相机", appName];
        // 展示提示语
        [BlockAlertView showAlertWithTitle:tipTextWhenNoPhotosAuthorization message:nil alertViewStyle:UIAlertViewStyleDefault block:^(id clickView, NSInteger index) {
            
        } cancelButtonTitle:@"确定" otherButtonTitles:nil];
        return NO;

    }else{
        return YES;

    }
}

+(void)playSound:(NSString*)name{
    NSURL *url=[[NSBundle mainBundle]URLForResource:name withExtension:nil];
    
    //2.加载音效文件，创建音效ID（SoundID,一个ID对应一个音效文件）
    SystemSoundID soundID=0;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
    
    //把需要销毁的音效文件的ID传递给它既可销毁
    //AudioServicesDisposeSystemSoundID(soundID);
    
    //3.播放音效文件
    //下面的两个函数都可以用来播放音效文件，第一个函数伴随有震动效果
//    AudioServicesPlayAlertSound(soundID);
    AudioServicesPlaySystemSound(soundID);
}

+(CGSize)getTextHeight:(NSString*)strText{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:14] forKey:NSFontAttributeName];
    CGSize size = [strText boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-60, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size;
}

//图片转字符串
+(NSString *)UIImageToBase64Str:(UIImage *) image
{
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

//字符串转图片
+(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr
{
//    NSData *_decodedImageData   = [[NSData alloc] initWithBase64Encoding:_encodedImageStr];
    NSData *_decodedImageData = [[NSData alloc] initWithBase64EncodedString:_encodedImageStr options:0];
    UIImage *_decodedImage      = [UIImage imageWithData:_decodedImageData];
    return _decodedImage;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (NSArray *)arrayWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+(NSString *)getMMSSFromSS:(NSString *)totalTime{
    
    NSInteger seconds = [totalTime integerValue];
    
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@小时%@分钟%@秒",str_hour,str_minute,str_second];
    
    return format_time;
    
}

+(float)getTabBarHeight{
    if(kDevice_Is_iPhoneX){
        return 83;
    }else{
        return 49;
    }
}

//+(UserInfo*)getUserInfoFromPlist{
//    NSDictionary *dic = [[FileOperator defaultOperator] userInfo];
//    UserInfo *personInfo = [UserInfo yy_modelWithDictionary:dic];
//    return personInfo;
//}

+(NSString*)formatDate:(NSString*)dateString{
    NSArray *array = [dateString componentsSeparatedByString:@"-"];
    return [NSString stringWithFormat:@"%@/%@/%@",array[0],array[1],array[2]];
}

+(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    return html;
}

+(NSString*)getBankName:(NSString*)name{
//    中国建设银行--CCB
//
//    中国农业银行--ABC
//
//    中国工商银行--ICBC
//
//    中国银行--BOC
//
//    中国民生银行--CMBC
//
//    招商银行--CMB
//
//    兴业银行--CIB
//
//    交通银行--BCM
//
//    中国光大银行--CEB
//
//    广东发展银行--GDB
//
//    中信银行--CITICIB
//
//    中国邮政银行--PSBC
//
//    中国平安银行--PABC
//
//    华夏银行--HB
    if ([name isEqualToString:@"CCB"]) {
        return @"中国建设银行";
    }else if ([name isEqualToString:@"ABC"]){
        return @"中国农业银行";
    }else if ([name isEqualToString:@"ICBC"]){
        return @"中国工商银行";
    }else if ([name isEqualToString:@"BOC"]){
        return @"中国银行";
    }else if ([name isEqualToString:@"CMBC"]){
        return @"中国民生银行";
    }else if ([name isEqualToString:@"CMB"]){
        return @"招商银行";
    }else if ([name isEqualToString:@"CIB"]){
        return @"兴业银行";
    }else if ([name isEqualToString:@"BCM"]){
        return @"交通银行";
    }else if ([name isEqualToString:@"CEB"]){
        return @"中国光大银行";
    }else if ([name isEqualToString:@"GDB"]){
        return @"广东发展银行";
    }else if ([name isEqualToString:@"CITICIB"]){
        return @"中信银行";
    }else if ([name isEqualToString:@"PSBC"]){
        return @"中国邮政银行";
    }else if ([name isEqualToString:@"PABC"]){
        return @"中国平安银行";
    }else if ([name isEqualToString:@"HB"]){
        return @"华夏银行";
    }else{
        return name;
    }
}

+(NSString*)getIconName:(NSString*)name{
    if ([name isEqualToString:@"schedule"]) {
        return @"scheduleIcon";
    }else if ([name isEqualToString:@"project"]){
        return @"investmentProjectIcon";
    }else if ([name isEqualToString:@"trip"]){
        return @"businessTravelIcon";
    }else if ([name isEqualToString:@"resource"]){
        return @"resourceIcon";
    }else if ([name isEqualToString:@"policy"]){
        return @"policyDocumentIcon";
    }else if ([name isEqualToString:@"flow"]){
        return @"businessProcessIcon";
    }else if ([name isEqualToString:@"document"]){
        return @"fileManagerIcon";
    }else if ([name isEqualToString:@"address"]){
        return @"connectIcon";
    }else if ([name isEqualToString:@"assets"]){
        return @"carrierInformationIcon";
    }else if ([name isEqualToString:@"disk"]){
        return @"cloudIcon";
    }else if ([name isEqualToString:@"meetingRoom"]){
        return @"bookMeetingIcon";
    }else if ([name isEqualToString:@"receiverDisk"]){
        return @"downFileIcon";
    }
    
    return @"";
}
+(UserInfo*)getUserInfo{
    NSDictionary *dic = [[FileOperator defaultOperator] userInfo];
    return [UserInfo yy_modelWithDictionary:dic];
}

+(NSDictionary*)objectToDictionary:(id)object{
    NSData *data = [object yy_modelToJSONData];
    NSDictionary *dic;
    if (data) {
         dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    }else{
         dic = [NSDictionary dictionary];
    }
    
    return dic;
}

+(NSString*)getIconImageName:(NSString*)name{
    if ([name isEqualToString:@"机位"]) {
        return @"main_machine_icon";
    }else if ([name isEqualToString:@"合同"]){
        return @"main_hetong_icon";

    }else if ([name isEqualToString:@"广告商"]){
        return @"main_guanggaoshang_icon";

    }else if ([name isEqualToString:@"代理商"]){
        return @"main_dailishang_icon";

    }else if ([name isEqualToString:@"渠道商"]){
        return @"main_qudaoshang_icon";

    }else if ([name isEqualToString:@"收益"]){
        return @"main_shouyi_icon";

    }else if ([name isEqualToString:@"报表"]){
        return @"main_baobiao_icon";

    }else if ([name isEqualToString:@"提醒"]){
        return @"main_notification_icon";

    }else if ([name isEqualToString:@"投资客户"]){
        return @"main_customer_icon";
    }else if ([name isEqualToString:@"咨询"]){
        return @"main_zixun_icon";
    }
    return @"";
}

+(NSArray*)getAllProvince{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"pcas-code" ofType:@"json"];
//    NSString *jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path options:0 error:nil];
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return array;
}

+(NSString*)getTimeFront:(NSString*)time{
    NSArray *array = [time componentsSeparatedByString:@" "];
    return array[0];
}

+(NSString*)replaceTimeString:(NSString*)timeString{
    return timeString = [timeString stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
}

+(float)getFloatFromString:(NSString*)string{
    if ([string isKindOfClass:[NSNull class]]) {
        return 0;
    }else{
        return [string floatValue];
    }
}

+(BOOL)getUserPermission:(NSString*)action{
    UserInfo *user = [self getUserInfo];
    NSArray *roleList = user.roleIdList;
    long role = [roleList[0] longValue];
    if (role == 9) {
        return YES;
    }else{
        if ([action isEqualToString:@"addmachine"]) {
            if (role == 12) {
                return YES;
            }else{
                return NO;
            }
        }else if ([action isEqualToString:@"contractreview"]){
            if (role == 12) {
                return YES;
            }else{
                return NO;
            }
        }else if ([action isEqualToString:@"addcontract"]){
            if (role == 12) {
                return YES;
            }else{
                return NO;
            }
        }else if ([action isEqualToString:@"addorg"]){
            if (role == 12) {
                return YES;
            }else{
                return NO;
            }
        }
    }
    
    return NO;
}


+ (NSObject *)removeNullFrom:(NSObject *)object
{
    NSObject *objResult = nil;
    NSMutableArray *marrSearch = nil;
    if ([object isKindOfClass:NSNull.class]) {
        return nil;
    }
    else if ([object isKindOfClass:NSArray.class]) {
        objResult = [NSMutableArray arrayWithArray:(NSArray *)object];
        marrSearch = [NSMutableArray arrayWithObject:objResult];
    }
    else if ([object isKindOfClass:NSDictionary.class]) {
        objResult = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)object];
        marrSearch = [NSMutableArray arrayWithObject:objResult];
    }
    else {
        return object;
    }
    while (marrSearch.count > 0) {
        NSObject *header = marrSearch[0];
        if ([header isKindOfClass:NSMutableDictionary.class]) {
            // 遍历这个字典
            NSMutableDictionary *mdicTemp = (NSMutableDictionary *)header;
            for (NSString *strKey in mdicTemp.allKeys) {
                NSObject *objTemp = mdicTemp[strKey];
                // 将NSDictionary替换为NSMutableDictionary
                if ([objTemp isKindOfClass:NSDictionary.class]) {
                    NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)objTemp];
                    mdicTemp[strKey] = mdic;
                    [marrSearch addObject:mdic];
                }
                // 将NSArray替换为NSMutableArray
                else if ([objTemp isKindOfClass:NSArray.class]) {
                    NSMutableArray *marr = [NSMutableArray arrayWithArray:(NSArray *)objTemp];
                    mdicTemp[strKey] = marr;
                    [marrSearch addObject:marr];
                }
                // 删除NSNull
                else if ([objTemp isKindOfClass:NSNull.class]) {
                    mdicTemp[strKey] = nil;
                }
            }
        }
        else if ([header isKindOfClass:NSMutableArray.class]) {
            // 遍历这个数组
            NSMutableArray *marrTemp = (NSMutableArray *)header;
            for (int i = marrTemp.count-1; i >= 0; i--) {
                NSObject *objTemp = marrTemp[i];
                // 将NSDictionary替换为NSMutableDictionary
                if ([objTemp isKindOfClass:NSDictionary.class]) {
                    NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)objTemp];
                    [marrTemp replaceObjectAtIndex:i withObject:mdic];
                    [marrSearch addObject:mdic];
                }
                // 将NSArray替换为NSMutableArray
                else if ([objTemp isKindOfClass:NSArray.class]) {
                    NSMutableArray *marr = [NSMutableArray arrayWithArray:(NSArray *)objTemp];
                    [marrTemp replaceObjectAtIndex:i withObject:marr];
                    [marrSearch addObject:marr];
                }
                // 删除NSNull
                else if ([objTemp isKindOfClass:NSNull.class]) {
                    [marrTemp removeObjectAtIndex:i];
                }
            }
        }
        else {
            // 到这里就出错了
        }
        [marrSearch removeObjectAtIndex:0];
    }
    return objResult;
}

@end
